const path = require('path');
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const rateLimit = require('express-rate-limit');

const { config } = require('./config');
const { apiRouter, healthRouter } = require('./routes');
const { notFoundHandler } = require('./middleware/notFound');
const { errorHandler } = require('./middleware/errorHandler');
const { httpLoggerStream, logger } = require('./utils/logger');

function resolveCorsOrigins(raw) {
  if (!raw || raw === '*') {
    return '*';
  }
  return raw.split(',').map((item) => item.trim()).filter(Boolean);
}

function createServer() {
  const app = express();

  app.disable('x-powered-by');
  app.use(helmet());
  app.use(cors({ origin: resolveCorsOrigins(config.allowOrigins) }));
  app.use(express.json({ limit: '5mb' }));
  app.use(express.urlencoded({ extended: true }));

  app.use(morgan(config.env === 'production' ? 'combined' : 'dev', { stream: httpLoggerStream }));

  const limiter = rateLimit({
    windowMs: config.rateLimit.windowMs,
    max: config.rateLimit.max,
    standardHeaders: true,
    legacyHeaders: false
  });
  app.use(limiter);

  const iconDir = path.resolve(__dirname, '../../../小图标');
  if (fs.existsSync(iconDir)) {
    app.use('/assets/icons', express.static(iconDir));
  } else {
    logger.warn({ iconDir }, 'Icon directory not found, skip mounting /assets/icons');
  }

  app.use('/health', healthRouter);
  app.use('/api', apiRouter);

  app.use(notFoundHandler);
  app.use(errorHandler);

  return app;
}

module.exports = { createServer };
